/*
 * Copyright 2018 Cnbbx Inc. All rights reserved.
 */

package com.cnbbx.consumer.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jinge
 * @apiNote AOP日志
 */
@Aspect
@Component
public class ConsumerLogAspect {

    private static Logger logger = LoggerFactory.getLogger(ConsumerLogAspect.class);

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Autowired
    protected HttpServletRequest request;

    @Pointcut("execution(public * com.cnbbx.consumer.controller..*(..))")
    public void aspect() {
    }

    @Before("aspect()")
    public void beforeMethod(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
    }

    @After("aspect()")
    public void afterMethod(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        logger.info("----->请求consumer URL={}, 处理完请求耗时={}", url, (System.currentTimeMillis() - startTime.get()) + "ms");
        startTime.remove();
    }

}
